<template>
  <div>
    <el-upload
        ref="upload"
        class="upload-demo"
        :action="uploadAction"
        :on-success="handleUploadSuccess"
        :show-file-list="false"
        accept=".jpeg,.png,.jpg,.bmp,.gif"
        drag
        :limit="limit"
        :before-upload="beforeUpload"
    >
      <div>
        <img v-if="imageUrl" :src="imageUrl" alt="上传图片" style="margin-top: 10px; max-width: 400px;"/>
        <div v-else>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            或拽文件或 <em>点击上传</em>
          </div>
        </div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import http from "@/util/http-util.js";

export default{
  name: 'ImageUploader',
  data(){
    return {
       uploadAction: http.genUrl("/upload"),
       imageUrl: undefined
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    limit:{
      type: Number,
      default: 1
    }
  },
  mounted() {
    if (this.value && this.value != "")
    this.imageUrl = http.genUrl(this.value.slice())
  },
  methods: {
    handleUploadSuccess(response, file) {
      // 假设服务器返回的数据包含图片的URL
      const imageUrl = response.data || '';
      // 通过 emit 事件更新父组件的 value
      this.$emit('change', imageUrl);
      this.imageUrl = http.genUrl(imageUrl);
      this.$refs.upload.clearFiles();
    },
    beforeUpload(file){
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!');
      }
      this.imageUrl = undefined;
      return isImage && isLt2M;
    }
  }
}
</script>

<style scoped>
.upload-demo {
  width: 400px;
}
</style>